package logic

import (
	"context"
	"fresh-box/models/mysql"
	"gorm.io/gorm"

	"fresh-box/freshrpc/freshrpc"
	"fresh-box/freshrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FreshAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshAddLogic {
	return &FreshAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品创建
func (l *FreshAddLogic) FreshAdd(in *freshrpc.FreshAddRequest) (*freshrpc.FreshAddResponse, error) {
	// todo: add your logic here and delete this line

	var fresh mysql.Fresh

	var sort mysql.Sort

	if err := sort.SortById(mysql.DB, in.SortId); err != nil {
		//return nil, errors.New("不存在该类型")
		sort := mysql.Sort{
			Model: gorm.Model{},
			Name:  in.Name,
		}

		if err := sort.SortAdd(mysql.DB); err != nil {
			return nil, err
		}
	}
	//
	//if err := fresh.TitleByFresh(mysql.DB, in.Title); err != nil {
	//	return nil, errors.New("已有该商品")
	//}

	fresh = mysql.Fresh{
		Model:  gorm.Model{},
		Title:  in.Title,
		Price:  float64(in.Price),
		SortId: int(in.SortId),
	}

	if err := fresh.FreshAdd(mysql.DB); err != nil {
		return nil, err
	}

	return &freshrpc.FreshAddResponse{
		FreshId: int64(fresh.ID),
	}, nil
}
